package com.happyclub.lbj.service.impl;

import com.happyclub.lbj.service.IActivityUserService;
import com.happyclub.lbjdao.SaveActivityUser;
import com.happyclub.lbjdao.SendActivity;
import com.happyclub.pojo.TbActivity;
import com.happyclub.pojo.TbActivityUser;
import com.happyclub.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

import java.util.Date;

import static com.happyclub.errormsg.ErrorMsgProvider.SYSTEM_BUSY;

/**
 * @author 高欢
 * @description TODO
 * @date 2019/4/5
 */
@Service
public class ActivityUserServiceImpl implements IActivityUserService {

    @Autowired
    SaveActivityUser saveActivityUser;
    @Autowired
    SendActivity sendActivity;

    @Transactional
    @Override
    public JsonResult insertActivityUser(TbActivityUser activityUser) {
        JsonResult jsonResult = new JsonResult();
        String activityId = activityUser.getActivityId();
        String userId = activityUser.getUserId();
        TbActivity activity1 = sendActivity.findById(activityId).get();
        /*System.out.println(activity1.getId());*/
        //报名活动之前,判断该用户与其他的活动的时间是否有冲突
        String s = saveActivityUser.ckeckUserActivity(userId, activity1.getActivityBeginTime());
        if (s!=null){
            jsonResult.setMsg("亲!该活动与您之前报名的活动存在冲突!无法报名...");
            jsonResult.setErrorCode("500");
            return jsonResult;
        }
        //向活动用户中间表中插入数据时,先查出活动限制报名人数
        int maxPeople = activity1.getActivityMaxPeople();
        //查看活动是否过期
        TbActivity activity = this.sendActivity.findTbActivityByIdAndActivityExpiredTimeAfter(activityId,new Date());
        if (activity==null){
            jsonResult.setErrorCode("500");
            jsonResult.setMsg("亲!活动已过期,无法报名!");
            return jsonResult;
        }
        //统计该活动已报名的人数
        long l = this.saveActivityUser.countByActivityId(activityId);
        if (maxPeople<=l){
            //此时人数已达上限
            jsonResult.setErrorCode("500");
            jsonResult.setMsg("亲!活动报名人数已达上限,无法报名!");
            return jsonResult;
        }
        TbActivityUser save = this.saveActivityUser.save(activityUser);
        if (save==null){
            jsonResult.setErrorCode("500");
            jsonResult.setMsg(SYSTEM_BUSY);
            return jsonResult;
        }
        return jsonResult;
    }

    @Transactional
    @Override
    public JsonResult cancelActivityByUser(String activityId, String userId) {
        JsonResult jsonResult = new JsonResult();
        int i = saveActivityUser.deleteTbActivityUserByActivityIdAndUserId(activityId, userId);
        if (i<=0){
            jsonResult.setMsg(SYSTEM_BUSY);
            jsonResult.setErrorCode("500");
            return jsonResult;
        }
        return jsonResult;
    }

}
